package org.jeecg.modules.aliyun.entity.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.jeecg.common.util.RestUtil;
import org.jeecg.modules.acmd.service.IAcmdService;
import org.jeecg.modules.aliyun.entity.run.SpringContextUtil;
import org.jeecg.modules.aliyun.entity.service.IEntityTaskService;
import org.jeecg.modules.demo.entity.Demo;
import org.jeecg.modules.demo.mapper.DemoMapper;
import org.jeecg.modules.phone.entity.*;
import org.jeecg.modules.phone.enums.TaskEnums;
import org.jeecg.modules.phone.mapper.*;
import org.jeecg.modules.system.util.sysUtils;
import org.jetbrains.annotations.Nullable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.socket.TextMessage;

import java.util.Date;
import java.util.List;
import java.util.concurrent.*;

import static java.lang.Thread.sleep;

/**
 * @Description: DemoDescript
 * @Author: jeecg-boot
 * @Date:   2022-08-09
 * @Version: V1.0
 */
@Service
public class EntityTaskServiceImpl extends ServiceImpl<DemoMapper, Demo> implements IEntityTaskService {

    @Autowired
    private PhoneEntityTaskMapper phoneEntityTaskMapper;

    @Autowired
    private PhoneEntityMapper phoneEntityMapper;

    @Autowired
    private IAcmdService acmdService;


    @Override
    @Scheduled(cron = "*/20 * * * * ?")
    public String checkOnline() {
        phoneEntityMapper.updateOffLine();
        System.out.println("20秒每次更新全员在线状态（断线1分的设为下线）。" + new Date().toString());
        return null;
    }

    @Override
    @Scheduled(cron = "*/10 * * * * ?")
    public String taskCheck()   {

//        System.out.println("-------------------------------开始检查EntityTask任务" + new Date().toString());


        /*这里每8秒只执行一条数据不能行，可能需要多线程来跑每台机的任务。 注释了53-64代码*/
        /*改成多线程执行多手机任务。*/
        System.out.println("10秒每次-------------------------------EntityTask check  " + new Date().toString());
        /*第一步先拿到有待执行任务（且没有执行中）的手机ID,按排序获取第一个待执行，并等待执行。*/
        /*但是如果上一条是报错状态不是完成状态，*/
        List<PhoneEntityTask> phoneEntityTaskList  = phoneEntityTaskMapper.checkWaitRunTask();


        phoneEntityTaskList.forEach(v->{
//             final String  phoneEntityTaskId = v.getEntityId();
//
//                    PhoneEntityTaskMapper phoneEntityTaskMapper =  SpringContextUtil.getBean(PhoneEntityTaskMapper.class);
//                    PhoneEntityTask phoneEntityTask  = phoneEntityTaskMapper.selectById(phoneEntityTaskId);
//                    System.out.println(phoneEntityTaskId);
//                    phoneEntityTask.setTaskStatus(TaskEnums.TaskStatus.RUN.getName());
//                    phoneEntityTaskMapper.updateById(phoneEntityTask);
//
//                    PhoneEntityTaskImplements pi = new PhoneEntityTaskImplements();
//                    pi.setPhoneEntityTask(phoneEntityTask,phoneEntityTaskMapper);
//                    new Thread(pi).start();
            System.out.println("-------------------------------EntityTask发现任务，"+ v.getEntityId() +":执行中");
            PhoneEntityTask phoneEntityTask  = v;
            phoneEntityTask.setTaskStatus(TaskEnums.TaskStatus.RUN.getName());
            phoneEntityTaskMapper.updateById(phoneEntityTask);

//            PhoneEntityTaskImplements pi = new PhoneEntityTaskImplements();
//            pi.setPhoneEntityTask(phoneEntityTask,phoneEntityTaskMapper);
//            new Thread(pi).start();

            JSONObject body = doPostTaskHx(phoneEntityTask);
            System.out.println("-------------------------------" + phoneEntityTask.getEntityId() + " 获取到命令并"+ body.getString("message"));

        });


        if(phoneEntityTaskList.size()==0){
            System.out.println("-------------------------------EntityTask未发现任务");
            return "未发现任务";
        }

        /*找到一个任务*/


        return "";
    }

    @Nullable
    private static JSONObject doPostTaskHx(PhoneEntityTask phoneEntityTask) {
        HttpHeaders requestHeaders = new HttpHeaders();
//            requestHeaders.add("X-Access-Token", loginToken);
        requestHeaders.add("content-type", MediaType.APPLICATION_JSON_UTF8.toString());
        JSONObject params = new JSONObject();
        params.put("id", phoneEntityTask.getId());

        ResponseEntity<JSONObject> responseEntity = RestUtil.request(
                "http://localhost:8080/spring-boot/phone/phoneEntityTask/taskHx",
                HttpMethod.POST , requestHeaders, null, params, JSONObject.class);
        JSONObject body = responseEntity.getBody();
        return body;
    }


//    @Override
//    @Scheduled(cron = "*/300 * * * * ?")
//    public String onlineCheck()   {
//        System.out.println("检查在线情况任务");
//        /*连接所有本网ip,这个开机就启动一次*/
//        checkAllEntity();
//        return "";
//    }

//    @Override
//    public String connectAll()   {
//        System.out.println("连接所有ip本网");
//        acmdService.doCmd(    "adb kill-server");
//        acmdService.doCmd(    "adb start-server");
//        checkAllEntity();
//        /*连接所有本网ip,这个开机就启动一次*/
//        return "";
//    }

//    private void checkAllEntity() {
//        List<PhoneEntity> phoneEntities = phoneEntityMapper.selectList(
//                new QueryWrapper<PhoneEntity>().lambda()
//                        .eq(PhoneEntity::getUpdateBy,sysUtils.serverName)
//        );
//        phoneEntities.forEach(v->{
//            new Thread(()->{
//                PhoneEntityMapper phoneEntityMapper = SpringContextUtil.getBean(PhoneEntityMapper.class);
//                PhoneAccountLogMapper phoneAccountLogMapper = SpringContextUtil.getBean(PhoneAccountLogMapper.class);
//                acmdService.doCmd("adb  connect " + v.getEntityIp() +":5555");
//                String entityStatus =  checkEntityOnlineByIp(v.getEntityIp())?
//                        EntityEnums.EntityStatus.ONLINE.getName()
//                        :EntityEnums.EntityStatus.OFFLINE.getName();
//                v.setEntityStatus(entityStatus);
//                phoneEntityMapper.updateById(v);
//                phoneAccountLogMapper.insert(
//                        new PhoneAccountLog()
//                                .setAccountId(v.getId())
//                                .setLogMsg("更新了在线状态:" + entityStatus)
//                );
//            }).start();
//
//        });
//    }

//    private boolean checkEntityOnlineByIp(String finalIp) {
//        /*转apk后，无需再检查IP。客户端没任务会自动更新自己的在线状态*/
//        String adb_if_config  = acmdService.doCmd("adb -s  " + finalIp +":5555  shell ifconfig wlan0 |findstr addr");
//        String str = adb_if_config;
//        String pattern = "inet addr:(\\S*)  Bcast:";
//        Pattern r = Pattern.compile(pattern);
//        Matcher m = r.matcher(str);
//        String ip="";
//        if(m.find()){
//            ip = m.group().replace("inet addr:", "").replace("  Bcast:", "");
//        }
//        return ip.equals(finalIp) ;
//    }


}
